import 'dart:async';
import 'dart:convert';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_with_up_or_down_arrows_dialog/common_with_up_or_down_arrows_dialog.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/check_in_statistics/check_in_statistics_page.dart';
import 'package:e_reception_flutter/ui/check_in_statistics/widgets/pages/check_dialog_value_bean.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'check_in_dialog_view_model.dart';

/// 打卡记录分类弹窗
///
/// @author: zengxiangxi
/// @createTime: 4/1/21 9:51 AM
/// @specialDemand:
class CheckInStatisticsClassifyButtonWidget extends StatefulWidget {
  const CheckInStatisticsClassifyButtonWidget({Key key}) : super(key: key);

  @override
  _CheckInStatisticsClassifyButtonWidgetState createState() =>
      _CheckInStatisticsClassifyButtonWidgetState();
}

class _CheckInStatisticsClassifyButtonWidgetState
    extends BaseState<CheckInStatisticsClassifyButtonWidget> {
  int departmentIdNum = 0;
  int classIdNum = 0;
  int deviceIdNum = 0;
  SelectedDepartmentViewModel viewModel;
  DepartmentAndClassDataBean departmentAndClassDataBean;

  CheckInStatisticsPageState pageState;
  @override
  void initState() {
    super.initState();
    departmentAndClassDataBean = DepartmentAndClassDataBean();
    viewModel = SelectedDepartmentViewModel(this);
    viewModel?.infoValueNotifier?.addListener(() {
      departmentAndClassDataBean = viewModel?.infoValueNotifier?.value;
    });
    viewModel?.getDayFaceRecord();
    pageState =
    CheckInStatisticsPageState.of(context);
  }


  @override
  Widget build(BuildContext context) {
    String typeStr = pageState?.classifyType?.getTypeToStr() ?? "筛选";
    if (pageState?.classifyType?.getTypeToStr() == "选择部门") {
      if(pageState?.departmentIds!=null && pageState?.departmentIds!=""){
        departmentIdNum = pageState?.departmentIds?.split(",")?.length ?? 0;
        if(departmentIdNum==1){
          typeStr = "已筛选：${VgStringUtils.subStringAndAppendSymbol((pageState?.departmentName ?? '暂无'), 12, symbol: "...")}";
        }else{
          typeStr = "已筛选：$departmentIdNum个部门";
        }
      }else{
        typeStr = "全部";
        pageState?.classifyType = CheckInStatisticsClassifyType.All;
        pageState?.departmentIds = null;
        pageState?.classIds = null;pageState?.deviceHsnList =null;
      }
        if((pageState?.classIds?.split(",")?.length ?? 0)!=0){
          typeStr = "已筛选：$classIdNum个班级";
          pageState?.classifyType = CheckInStatisticsClassifyType.Class;
        }else if((pageState?.deviceHsnList?.split(",")?.length ?? 0)!=0){
          typeStr = "已筛选：$deviceIdNum个终端";
          pageState?.classifyType = CheckInStatisticsClassifyType.Device;
        }else if(departmentIdNum==0){
            typeStr = "全部";
            pageState?.classifyType = CheckInStatisticsClassifyType.All;
            pageState?.departmentIds = null;
            pageState?.classIds = null;pageState?.deviceHsnList =null;
          }
    }else if (pageState?.classifyType?.getTypeToStr() == "选择班级") {
      if(pageState?.classIds!=null && pageState?.classIds!=""){
        classIdNum = pageState?.classIds?.split(",")?.length ?? 0;
        if(classIdNum==1){
          typeStr = "已筛选：${VgStringUtils.subStringAndAppendSymbol((pageState?.departmentName ?? '暂无'), 12, symbol: "...")}";
        }else{
          typeStr = "已筛选：$classIdNum个班级";
        }
      }else{
        typeStr = "全部";
        pageState?.classifyType = CheckInStatisticsClassifyType.All;
        pageState?.departmentIds = null;
        pageState?.classIds = null;pageState?.deviceHsnList =null;
      }

      if((pageState?.departmentIds?.split(",")?.length ?? 0)!=0){
        typeStr = "已筛选：$departmentIdNum个部门";
        pageState?.classifyType = CheckInStatisticsClassifyType.Department;
      }else if((pageState?.deviceHsnList?.split(",")?.length ?? 0)!=0){
        typeStr = "已筛选：$deviceIdNum个终端";
        pageState?.classifyType = CheckInStatisticsClassifyType.Device;
      }else if(classIdNum==0){
        typeStr = "全部";
        pageState?.classifyType = CheckInStatisticsClassifyType.All;
        pageState?.departmentIds = null;
        pageState?.classIds = null;pageState?.deviceHsnList =null;
      }
    }else if (pageState?.classifyType?.getTypeToStr() == "刷脸设备") {
      if(pageState?.deviceHsnList!=null && pageState?.deviceHsnList!=""){
        deviceIdNum = pageState?.deviceHsnList?.split(",")?.length ?? 0;
        if(deviceIdNum==1){
          typeStr = "已筛选：${(pageState?.departmentName ?? '暂无')}";
        }else{
          typeStr = "已筛选：$deviceIdNum个设备";
        }
      }else{
        typeStr = "全部";
        pageState?.classifyType = CheckInStatisticsClassifyType.All;
        pageState?.departmentIds = null;
        pageState?.classIds = null;
        pageState?.deviceHsnList =null;
      }

      if((pageState?.departmentIds?.split(",")?.length ?? 0)!=0){
        typeStr = "已筛选：$departmentIdNum个部门";
        pageState?.classifyType = CheckInStatisticsClassifyType.Department;
      }else if((pageState?.classIds?.split(",")?.length ?? 0)!=0){
        typeStr = "已筛选：$classIdNum个班级";
        pageState?.classifyType = CheckInStatisticsClassifyType.Class;
      }else if(deviceIdNum==0){
        typeStr = "全部";
        pageState?.classifyType = CheckInStatisticsClassifyType.All;
        pageState?.departmentIds = null;
        pageState?.classIds = null;
        pageState?.deviceHsnList =null;
      }
    }else if(pageState?.classifyType?.getTypeToStr() == "特别关注"){
      pageState?.departmentIds = null;
      pageState?.classIds = null;pageState?.deviceHsnList =null;
    }else{
      pageState?.departmentIds = null;
      pageState?.classIds = null;pageState?.deviceHsnList =null;
    }
    typeStr =  typeStr.characters.join("\u{200B}");
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        Future.delayed(Duration(milliseconds: 100), () async {
          CheckInStatisticsClassifyType classifyType =
              await _CompanyDetailFilterButtonMenuDialog.navigatorPushDialog(
              context, pageState?.classifyType,_dialogMaxHeight(),departmentAndClassDataBean);
          if (classifyType != null) {
            pageState?.changeClassifyType(classifyType);
          }
        });

      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 15),
        alignment: Alignment.center,
        child: Row(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(top: 1),
              child: Image.asset(
                "images/shaixuan.png",
                width: 16,
                color: Color(0xFFD0E0F7),
              ),
            ),
            SizedBox(width: 3),
            Expanded(
              child: Text(
                typeStr == "全部" ?"筛选" :typeStr,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: VgColors.INPUT_BG_COLOR,
                  // StringUtils.isNotEmpty(pageState?.classifyType?.getTypeToStr())
                  // ? ThemeRepository.getInstance().getPrimaryColor_1890FF()
                  // ? VgColors.INPUT_BG_COLOR
                  // : VgColors.INPUT_BG_COLOR,
                  fontSize: 12,
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  double _dialogMaxHeight(){
    double value = 250;
    if((departmentAndClassDataBean?.SpecialCnt??0)==0){
      value = value - 50;
    }
    if((departmentAndClassDataBean?.MDepartmentCnt??0)==0){
      value = value - 50;
    }
    if((departmentAndClassDataBean?.MClassCnt??0)==0){
      value = value - 50;
    }
    if((departmentAndClassDataBean?.MHsnCnt??0)==0){
      value = value - 50;
    }
    return value;
  }
}

/// 打卡记录分类菜单弹窗
///
/// @author: zengxiangxi
/// @createTime: 4/1/21 9:51 AM
/// @specialDemand:
class _CompanyDetailFilterButtonMenuDialog extends StatefulWidget {
  final CheckInStatisticsClassifyType classifyType;
  final DepartmentAndClassDataBean departmentAndClassDataBean;
  _CompanyDetailFilterButtonMenuDialog({
    Key key,
    this.classifyType, this.departmentAndClassDataBean,
  }) : super(key: key);
  static Future<CheckInStatisticsClassifyType> navigatorPushDialog(
      BuildContext context, CheckInStatisticsClassifyType classifyType,double height,DepartmentAndClassDataBean departmentAndClassDataBean) {
    return CommonWithUpOrDownArrowsDialog.navigatorPushForDialog<
            CheckInStatisticsClassifyType>(context,
        dialogMaxHeight: height ?? 250,
        arrowsSize: Size(11, 6),
        safeY: 0,
        arrowsOffsetX: 26,
        dialogToBoxOffsetY: -8,
        arrowsColor: Color(0xFF303546),
        child: Align(
          alignment: Alignment.centerLeft,
          child:
              _CompanyDetailFilterButtonMenuDialog(classifyType: classifyType,departmentAndClassDataBean:departmentAndClassDataBean),
        ));
  }

  @override
  __CompanyDetailFilterButtonMenuDialogState createState() =>
      __CompanyDetailFilterButtonMenuDialogState();
}

class __CompanyDetailFilterButtonMenuDialogState
    extends BaseState<_CompanyDetailFilterButtonMenuDialog> {

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 8),
      decoration: BoxDecoration(
        color: Color(0xFF303546),
        borderRadius: BorderRadius.circular(12),
      ),
      // height: 200,
      width: 160,
      child: Column(
        mainAxisSize: MainAxisSize.max,
        children: <Widget>[
          Spacer(),
          _toListItemWidget(
              context,
              CheckInStatisticsClassifyType.All.getTypeToStr(),
              0,
              widget.classifyType == CheckInStatisticsClassifyType.All, () {
            RouterUtils.pop(context, result: CheckInStatisticsClassifyType.All);
          }, () {
            //清空缓存
            SharePreferenceUtil.putString(
                "sp_check_in_is_very_classIds" +
                    UserRepository.getInstance().getCompanyId(),
                "");
            SharePreferenceUtil.putString(
                "sp_check_in_is_very_departmentIds" +
                    UserRepository.getInstance().getCompanyId(),
                "");
            SharePreferenceUtil.putString(
                "sp_check_in_is_very_deviceHsn" +
                    UserRepository.getInstance().getCompanyId(),
                "");
          }),
          if((widget?.departmentAndClassDataBean?.MDepartmentCnt??0) != 0)
          _toListItemWidget(
              context,
              CheckInStatisticsClassifyType.Department.getTypeToStr(),
              0,
              widget.classifyType == CheckInStatisticsClassifyType.Department,
              () {
            RouterUtils.pop(context,
                result: CheckInStatisticsClassifyType.Department);
          }, () {
            //跳转到部门选择
            VgEventBus.global.send(DepartmentIdsRefreshEvent(
                widget?.departmentAndClassDataBean?.MDepartmentList));
          }),
          if((widget?.departmentAndClassDataBean?.MClassCnt??0) != 0)
          _toListItemWidget(
              context,
              CheckInStatisticsClassifyType.Class.getTypeToStr(),
              0,
              widget.classifyType == CheckInStatisticsClassifyType.Class, () {
            RouterUtils.pop(context,
                result: CheckInStatisticsClassifyType.Class);
          }, () {
            VgEventBus.global.send(
                ClassIdsRefreshEvent(widget?.departmentAndClassDataBean?.MClassList));
          }),
          if((widget?.departmentAndClassDataBean?.MHsnCnt??0) != 0)
            _toListItemWidget(
                context,
                CheckInStatisticsClassifyType.Device.getTypeToStr(),
                0,
                widget.classifyType == CheckInStatisticsClassifyType.Device, () {
              RouterUtils.pop(context,
                  result: CheckInStatisticsClassifyType.Device);
            }, () {
              VgEventBus.global.send(
                  DeviceIdsRefreshEvent(widget?.departmentAndClassDataBean?.MHsnList));
            }),
          if((widget?.departmentAndClassDataBean?.SpecialCnt??0) != 0)
          _toListItemWidget(
              context,
              CheckInStatisticsClassifyType.VeryCare.getTypeToStr(),
              0,
              widget.classifyType == CheckInStatisticsClassifyType.VeryCare,
              () {
            RouterUtils.pop(context,
                result: CheckInStatisticsClassifyType.VeryCare);
          }, () {
            //清空缓存
            SharePreferenceUtil.putString(
                "sp_check_in_is_very_classIds" +
                    UserRepository.getInstance().getCompanyId(),
                "");
            SharePreferenceUtil.putString(
                "sp_check_in_is_very_departmentIds" +
                    UserRepository.getInstance().getCompanyId(),
                "");
            SharePreferenceUtil.putString(
                "sp_check_in_is_very_deviceHsn" +
                    UserRepository.getInstance().getCompanyId(),
                "");
          }),
          Spacer(),
        ],
      ),
    );
  }

  Widget _toListItemWidget(BuildContext context, String title, int personcnt,
      bool isSelected, VoidCallback onTap, VoidCallback onTapToNewPage) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        onTap?.call();
        if (onTapToNewPage != null) onTapToNewPage?.call();
      },
      child: Container(
        height: 44,
        width: 160,
        child: Center(
          child: Row(
            mainAxisSize: MainAxisSize.max,
            children: <Widget>[
              SizedBox(
                width: 20,
              ),
              Container(
                // width: 52,
                alignment: Alignment.centerLeft,
                child: Text(
                  title ?? "",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: isSelected
                        ? ThemeRepository.getInstance().getPrimaryColor_1890FF()
                        : Color(0xFFD0E0F7),
                    fontSize: 14,
                  ),
                ),
              ),
              Spacer(),
              if (title != "全部")
                _toDepartmentAndClass(isSelected, title),
              if (title == "全部")
                Opacity(
                    opacity: isSelected ? 1 : 0,
                    child: Image.asset(
                      "images/current_ico.png",
                      width: 13,
                    )),
              SizedBox(
                width: 12,
              ),
            ],
          ),
        ),
      ),
    );
  }

  int _classOrDepartmentNum(String title) {
    if (title == "选择部门") {
      return widget?.departmentAndClassDataBean?.MDepartmentCnt ?? 0;
    }
    if (title == "选择班级") {
      return widget?.departmentAndClassDataBean?.MClassCnt ?? 0;
    }
    if (title == "刷脸设备") {
      return widget?.departmentAndClassDataBean?.MHsnCnt ?? 0;
    }
    if (title == "特别关注") {
      return widget?.departmentAndClassDataBean?.SpecialCnt ?? 0;
    }
  }

  Widget _toDepartmentAndClass(bool isSelected, String title) {
    return Row(
      children: <Widget>[
        Text(
          "${_classOrDepartmentNum(title) == 0 ? "" : _classOrDepartmentNum(title)}",
          style: TextStyle(
              color: isSelected
                  ? ThemeRepository.getInstance().getPrimaryColor_1890FF()
                  : Color(0xFFD0E0F7),
              fontSize: 14),
        ),
        SizedBox(
          width: 6,
        ),
        Opacity(
          opacity: title != "特别关注" ? 1 : 0,
          child: Image.asset(
            "images/index_arrow_ico.png",
            width: 6,
            height: 11,
            color: ThemeRepository.getInstance().getHintGreenColor_5E687C()
                ,
          ),
        ),
      ],
    );
  }
}

///筛选分组
///00未选 01选择
enum CheckInStatisticsClassifyType {
  All, //所有
  VeryCare, //特别关心
  Department,
  Class,
  Device
}

extension CheckInStatisticsClassifyTypeExtension
    on CheckInStatisticsClassifyType {
  String getTypeToStr() {
    switch (this) {
      case CheckInStatisticsClassifyType.All:
        return "全部";
      case CheckInStatisticsClassifyType.Department:
        return "选择部门";
      case CheckInStatisticsClassifyType.Class:
        return "选择班级";
      case CheckInStatisticsClassifyType.Device:
        return "刷脸设备";
      case CheckInStatisticsClassifyType.VeryCare:
        return "特别关注";
    }
    return null;
  }

  ///00未选 01选择
  String getTypeToId() {
    switch (this) {
      case CheckInStatisticsClassifyType.All:
        return "00";
      case CheckInStatisticsClassifyType.Department:
        return "03";
      case CheckInStatisticsClassifyType.Class:
        return "02";
      case CheckInStatisticsClassifyType.Device:
        return "04";
      case CheckInStatisticsClassifyType.VeryCare:
        return "01";
    }
    return "00";
  }
}

class ClassIdsRefreshEvent {
  List<MClassListBean> MClassList;

  ClassIdsRefreshEvent(this.MClassList);
}

class DeviceIdsRefreshEvent {
  List<MHsnListBean> MHsnList;

  DeviceIdsRefreshEvent(this.MHsnList);
}

class DepartmentIdsRefreshEvent {
  List<MDepartmentListBean> mDepartment;

  DepartmentIdsRefreshEvent(this.mDepartment);
}
